<template>
  <div class="userSet">
    <!-- <el-col :span="12"> -->
    <div class="basic-circle">
      <div class="block">
        <el-avatar :size="200" :src="avatar"></el-avatar>
      </div>
      <el-upload
        class="upload"
        action="http://127.0.0.1:1018/upload"
        :limit="1"
        :on-success="handleSuccess"
        :file-list="fileList"
      >
        <div class="sub-button">
          <el-button size="small" type="primary">更换头像</el-button>
          <div class="sub-title">{{ userName }}</div>
          <div class="sub-title sub-title2">
            {{ power ? "管理员" : "普通用户" }}
          </div>
        </div>
      </el-upload>
    </div>
    <!-- </el-col> -->
  </div>
</template>

<script>
import { postFunc } from "@/utils/http.js";
export default {
  data() {
    return {
      img: "",
      fileList: [],
    };
  },
  computed: {
    avatar() {
      return this.$store.state.user.avatar;
    },
    id() {
      return this.$store.state.user.id;
    },
    userName() {
      return this.$store.state.user.userName;
    },
    power() {
      return this.$store.state.user.power;
    },
  },
  methods: {
    setAvatar(avatar) {
      if (avatar) {
        // console.log(this.form);
        let id = this.id;
        postFunc("/user/setAvatar", {
          avatar,
          id,
        }).then((data) => {
          // 上传成功
          if (data.code == 200) {
            // console.log(data);
            this.$message({
              message: "更改成功",
              type: "success",
            });
            this.img = data.avatar;
            this.$store.dispatch("user/setAvatarAsync", data.avatar);
          } else {
            console.log(data);
          }
        });
      } else {
        return;
      }
    },
    handleSuccess(response, file, fileList) {
      let url = response.url.split("\\")[2];
      this.img = response.url;
      this.setAvatar(url);
    },
  },
  mounted() {
    this.img = this.avatar;
  },
};
</script>

<style lang='scss'>
.userSet {
  .sub-title {
    text-align: center;
    margin: 5px auto;
  }
  .sub-title2 {
    color: #aaa;
    font-size: 14px;
  }
  .sub-button {
    margin: 0 60px;
  }
  .basic-circle {
    margin: 0 115px;
  }
}
</style>